import { Group, Tips } from 'butterfly-dag'
import $ from 'jquery'
import _ from 'lodash'

class BaseGroup extends Group {
  [x: string]: any

  expand: boolean = true

  constructor(opts) {
    super(opts)
    this._emit = opts._emit
    this.expand = opts.expand || true
  }

  mounted = () => {
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    const _self = this
    $(this.dom)
      .find('.icon')
      .click((e) => {
        if (_self.expand) {
          $(e.target).removeClass('bi-chevron-down')
          $(e.target).addClass('bi-chevron-up')
          $(_self.dom).find('.container').hide()
          $(_self.dom).find('.text').addClass('titlt-expend')
          _self.expand = false
          _self.emit('groupExpandEvent', {
            id: _self.id,
            expand: _self.expand
          })
        } else {
          $(e.target).addClass('bi-chevron-down')
          $(e.target).removeClass('bi-chevron-up')
          $(_self.dom).find('.container').show()
          $(_self.dom).find('.text').removeClass('titlt-expend')
          _self.expand = true
          _self.emit('groupExpandEvent', {
            id: _self.id,
            expand: _self.expand
          })
        }
      })

    this.on('onUpdateGroupEvent', (data) => {
      if (data.id == _self.id) {
        _self.options.text = data.text
        const $dom = $(_self.dom).find('.title')
        $dom.text(data.text)
        $dom.attr('title', data.text)
      }
    })
  }

  draw(obj) {
    let _dom = obj.dom
    if (!_dom) {
      _dom = $('<div></div>')
        .attr('class', 'group')
        .css('top', obj.top)
        .css('left', obj.left)
        .css('width', obj.width)
        .css('height', obj.height)
        .attr('id', obj.id)
    }
    const group = $(_dom)
    this._container = $('<div></div>').attr('class', 'container')

    group.append(this._container)

    // 添加文字
    if (_.get(obj, 'options.text')) {
      group.append(
        `<div class="text" ><div class="title " title='${obj.options.text}'>${obj.options.text}</div><i class="icon bi bi-chevron-down"></i></div>`
      )
    }
    this.setResize(true, this._container)
    const _id = obj.id
    const _text = obj.options.text
    group.dblclick(() => {
      this.emit('onModifyGroupEvent', {
        id: _id,
        text: obj.options.text
      })
    })
    return _dom
  }

  getWidth = () => {
    return $(this.dom).width()
  }
  getHeight = () => {
    return $(this.dom).height()
  }

  emit(event, data) {
    super.emit(event, data)
    this._emit = this._emit
  }
}

export default BaseGroup
